package org.tg.home.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tg.client.SearchFeignClient;
import org.tg.client.activity.ActivityFeignClient;
import org.tg.client.product.ProductFeignClient;
import org.tg.client.seckill.SeckillFeignClient;
import org.tg.home.service.ItemService;
import org.tg.vo.activity.SeckillSkuVo;
import org.tg.vo.product.SkuInfoVo;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author Glow
 * @Date 2023-07-21 11:32:09
 * @Description
 * @Version 1.0
 */
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ActivityFeignClient activityFeignClient;

    @Autowired
    private SeckillFeignClient seckillFeignClient;

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public Map<String, Object> item(Long skuId, Long userId) {
        Map<String,Object> result = new HashMap<>();
        //通过skuId查询skuInfo
        CompletableFuture<SkuInfoVo> skuInfoVoCompletableFuture
                = CompletableFuture.supplyAsync(()->{
                    //sku基本信息
            SkuInfoVo skuInfoVo = productFeignClient.getSkuInfoVo(skuId);
            result.put("skuInfoVo",skuInfoVo);
            return skuInfoVo;
        },threadPoolExecutor);
        //如果商品是秒杀商品，获取秒杀信息
        CompletableFuture<SeckillSkuVo> seckillSkuVoCompletableFuture
                = CompletableFuture.supplyAsync(()->{
                    SeckillSkuVo seckillSkuVo = activityFeignClient.getSeckillSkuVo(skuId);
                    result.put("seckillSkuVo",seckillSkuVo);
                    return seckillSkuVo;
        },threadPoolExecutor);
        //根据skuId和userId获取用户对应的活动信息和优惠券信息
        CompletableFuture<Void> activityCompletableFuture =
                CompletableFuture.runAsync(()->{
                    Map<String,Object> activityandCouponMap = activityFeignClient.findActivityAndCoupon(skuId, userId);
                    result.putAll(activityandCouponMap);
                },threadPoolExecutor);
        CompletableFuture<Void> hotCompletableFuture = CompletableFuture.runAsync(() -> {
            searchFeignClient.incrHotScore(skuId);
        },threadPoolExecutor);
        CompletableFuture.allOf(
                skuInfoVoCompletableFuture,
                seckillSkuVoCompletableFuture,
                activityCompletableFuture,
                hotCompletableFuture
                ).join();
        return result;
    }
}
